<!-- echart 折线图 -->
<template>
  <div id="echartsLine" ref="echartsLine" class="box" />
</template>

<script>
import echarts from "echarts";
import { formatMoney } from "@/utils/common.js";
import { mapGetters } from "vuex";
import variables from "@/styles/black/variables.scss";
const options = {
  tooltip: {
    trigger: "axis",
    backgroundColor: variables.tooptipBgColor,
    // axisPointer: {
    //   type: "shadow", // hover移入的样式
    //   label: {
    //     show: true,
    //   },
    // },
  },
  title: {
    show: false,
    text: "",
  },
  toolbox: {
    show: true,
    top: 10,
    right: 20,
    showTitle: false,
    iconStyle: {
      borderColor: variables.iconColor,
    },
    feature: {
      saveAsImage: {
        show: true,
        excludeComponents: ["toolbox"],
        pixelRatio: 2,
        backgroundColor: variables.linehightColor,
      },
    },
  },
  calculable: true,
  animation: true,
  legend: {
    type: "scroll",
    orient: "horizontal",
    pageIconColor: variables.iconColor,
    pageIconInactiveColor: variables.linehightColor,
    pageTextStyle: {
      color: variables.textColor,
    },
    width: 450,
    data: [],
    formatter: function (name) {
      return name;
    },
    selected: {},
    itemGap: 10,
    itemWidth: 14,
    itemHeight: 2,
    right: 60,
    top: 15,
    // top: "2%",
    // bottom: '10%'
    // selectedMode: false,
    icon: "rect",
    textStyle: {
      fontSize: 12,
    },
  },
  grid: {
    top: "20%",
    left: "8%",
    right: "3%",
    bottom: "10%",
    // containLabel: true,
  },
  xAxis: [
    {
      type: "category",
      // splitNumber: 100
      data: [],
      nameTextStyle: {
        color: variables.textColor,
      },
      axisLabel: {
        interval: "auto",
        color: variables.textColor,
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: variables.xyLineBgColor,
          width: 1,
          type: "solid",
        },
      },
    },
  ],
  yAxis: [],
  dataZoom: [
    {
      type: "inside",
      start: 50,
      end: 80,
      // minSpan: 10,
      // maxSpan: 20,
      // disabled:false,
      throttle: 500,
    },
  ],
  series: [],
};
export default {
  name: "",
  components: {},
  props: {
    list: {
      type: Array,
      default: () => {},
    },
    echartsData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      echarts1: null,
      name: [],
    };
  },
  computed: {
    // 监听store中数据变化
    ...mapGetters(["isCollapse"]),
    menuIsCollapse() {
      return this.isCollapse;
    },
  },
  watch: {
    menuIsCollapse: {
      handler(newValue, oldValue) {
        this.getData();
      },
      deep: true,
    },
    echartsData: {
      handler: function (newValue, oldValue) {
        this.getData();
      },
      deep: true,
      // immediate: true
    },
  },
  created() {},
  mounted() {
    this.getData();
    window.onresize = () => {
      this.getData();
    };
    window.addEventListener("resize", () => {
      this.getData();
    });
  },
  activated() {
    this.getData();
  },
  beforeDestroy() {
    if (this.echarts1) {
      this.echarts1.clear();
    }
  },
  destroyed() {
    if (this.echarts1) {
      this.echarts1.dispose();
    }
  },
  // deactivated() {
  //   console.log("deactivated页面关闭时触发");
  // },
  methods: {
    getData() {
      this.name = this.list.map((item) => item.name);
      const serArr = [];
      const lenArr = [];
      const yArr = [];
      const seriesData = [];
      const lengdData = [];
      const yAxis = [];
      this.list.forEach((item, index) => {
        const obj = {
          name: item.name,
          type: "line",
          symbol: "none", // 去掉折线上的小圆点
          yAxisIndex: index,
          label: {
            name: item.unit,
          },
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(
                0,
                1,
                0,
                0,
                [
                  {
                    offset: 0,
                    color: item.color0, // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: item.color1, // 100% 处的颜色
                  },
                ],
                false
              ),
            },
          },
          // data: []
          data: this.echartsData[item.acronym]
            ? this.echartsData[item.acronym]
            : [],
        };
        const len = {
          name: item.name,
          textStyle: {
            color: variables.textColor,
          },
        };
        const yax = {
          id: index,
          show: true,
          type: "value",
          axisLabel: {
            // show: true
            formatter: function (value, index) {
              // return value > 1000 ? value / 10000 + "w" : value;
              if (value > 1000 || value < -1000) {
                return value / 10000 + "w";
              } else {
                return value;
              }
            },
          },
          // 刻度的间隔
          // interval: 20,
          name: item.unit,
          offset: 0 * 40,
          position: "left",
          nameTextStyle: {
            color: item.color1,
          },
          nameGap: 23,
          // nameLocation:'end',
          // 设置y轴
          axisLine: {
            show: true,
            lineStyle: {
              color: item.color1,
              width: 1,
              type: "solid",
            },
          },
          // 设置y轴的刻度线
          axisTick: {
            // show: index == 1 ? true : false,
            show: true,
            inside: true,
            lineStyle: {
              type: "solid",
            },
          },
          // 设置背景线为虚线
          splitLine: {
            // show: index == 1 ? true : false,
            show: false,
            lineStyle: {
              type: "dashed",
            },
          },
        };
        seriesData.push(obj);
        lengdData.push(len);
        yAxis.push(yax);
      });
      seriesData.forEach((item) => {
        serArr.push(item);
      });
      lengdData.map((item) => {
        lenArr.push(item);
      });
      serArr.forEach((item, index) => {
        const name = item.name;
        if (this.name.indexOf(item.name) != -1) {
          const i = this.name.indexOf(item.name);
          item.yAxisIndex = index;
          if (index != 0) {
            yAxis[i].offset = index * 45;
          } else {
            // yAxis[i].axisTick.show = true;
            yAxis[i].splitLine.show = true;
            yAxis[i].offset = 0;
          }
          yArr.push(yAxis[i]);
        }
      });
      options.series = serArr;
      options.legend.data = lenArr;
      options.yAxis = yArr;

      let y = 3;
      let g = 7.5;
      if (window.innerWidth <= 1680 && window.innerWidth > 1380) {
        y = 3.8;
        g = 8.5;
      } else if (window.innerWidth <= 1745 && window.innerWidth > 1680) {
        y = 3.3;
        g = 8.5;
      } else if (window.innerWidth < 1380) {
        y = 5;
        g = 9.5;
      } else if (window.innerWidth > 1920 && window.innerWidth <= 2133) {
        y = 2.8;
        g = 7.5;
      } else if (window.innerWidth > 2133) {
        y = 2.5;
        g = 7.5;
      }
      if (yArr.length == 2) {
        yArr[1].position = "right";
        yArr[1].offset = 0;
        yArr[0].offset = 0;
        options.grid.left = y + "%";
        options.grid.right = y + 1 + "%";
      } else if (yArr.length == 1) {
        options.grid.left = y + "%";
      } else {
        options.grid.left = y * yArr.length - 0.5 + "%";
      }
      options.xAxis[0].data = [];
      options.xAxis[0].data = this.echartsData.xdate;
      options.title.text = this.echartsData.title;
      this.echarts1 = echarts.init(document.getElementById("echartsLine"));
      this.echarts1.on("legendselectchanged", function (params) {
        let first = true;
        options.series.forEach((item, i) => {
          if (first && params.selected[item.name]) {
            first = false;
            options.yAxis[i].splitLine.show = true;
          } else {
            options.yAxis[i].splitLine.show = false;
          }
        });
        this.setOption(options);
      });
      if (
        options.series[0] &&
        options.series[0].data &&
        options.series[0].data.length <= 50
      ) {
        options.dataZoom[0].start = 0;
        options.dataZoom[0].end = 100;
      } else {
        options.dataZoom[0].start = 50;
        options.dataZoom[0].end = 60;
      }
      const title = this.echartsData.title;
      options.tooltip.formatter = function (params) {
        let res = "";
        let res1 = "";
        let lastName = "";
        const moneys = [
          "分销金额",
          "持仓量",
          "算数平均票面1",
          "交易金额",
          "发行金额",
          "承销份额",
          "中标总量",
          "交易量",
          "估值模拟",
        ];
        const hour = [
          "平均持仓天数（自然日）",
          "最大持仓天数（自然日）",
          "平均持仓天数（工作日）",
          "最大持仓天数（工作日）",
          "最大持有天数",
          "平均持有天数",
          "最大处置时长",
          "平均处置时长",
        ];
        const money = [
          "总体销售佣金",
          "已收销售佣金",
          "应收销售佣金",
          "单位中标量的销售佣金",
          "销售佣金",
          "算数平均票面",
          "净承销费",
          "当日持仓利润",
          "累计持仓利润",
          "团费支出",
          // 首页新增
          "财务损益",
          "利息收入",
          "包销户余额",
          "价差损益",
        ];
        const BP = [
          "算数平均费率",
          "算数平均销售佣金费率",
          "最大估值偏离",
          "平均估值偏离",
        ];
        const thousandMoney = ["价差损益", "财务损益", "总损益", "接入量"];
        const noUnit = [];
        const moneyUnit = ["万元", "亿元", "元"];
        for (var j = 0; j < params.length; j++) {
          res = params[j].seriesName;
          if (res == "债券只数") {
            lastName = "只";
          } else if (moneys.includes(res)) {
            lastName = "亿元";
            if (title == "当日持仓分析" && res == "持仓量") lastName = "万元";
          } else if (money.includes(res)) {
            lastName = "元";
          } else if (hour.includes(res)) {
            lastName = "天";
          } else if (BP.includes(res)) {
            lastName = "BP";
          } else if (thousandMoney.includes(res)) {
            lastName = "万元";
          } else {
            lastName = "%";
          }
          res1 += `<div class="tooptip-body">
                            <div class="tooptip-label">
                              <span class="tooptip-label-icon-line" style="background:linear-gradient(360deg, ${
                                params[j].color.colorStops[0].color
                              } 0%, ${
            params[j].color.colorStops[1].color
          } 100%);"></span>
                              <span>${res}</span>
                            </div>
                            <div>
                             <span class="tooptip-value">${
                               moneyUnit.includes(lastName)
                                 ? formatMoney(params[j].value)
                                 : params[j].value
                             }</span>
                             <span class="tooptip-unit">${lastName}</span>
                            </div>
                          </div>`;
        }
        var htmlStr = `
              <div class="tooptip-info">
                <div class="tooptip-title">${params[0].name}</div>
                <div class="tooptip-content">
                  ${res1}
                </div>
              </div>
            `;
        return htmlStr;
      };
      this.echarts1.setOption(options, true);
      setTimeout(() => {
        this.echarts1.resize();
      }, 500);
    },
  },
};
</script>

<style scoped lang="scss">
// 解决echarts resize不生效问题
::v-deep.box {
  width: 100%;
  height: 100%;
  min-height: 300px;
  // 子选择器(>) :只能选择作为某元素儿子元素的元素（直接子元素），不包括孙元素、曾孙元素等等等
  & > div:first-child {
    width: 100% !important;
    height: 100% !important;
    min-height: 300px;
    canvas {
      width: 100% !important;
      height: 100% !important;
      min-height: 300px;
    }
  }
}
</style>
